package com.base.controller.utils.Md5;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

public class Md5EncryptUtils {
//   private static final char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6',
//     '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
//
//   public static String md5(String text)
//   {
//     MessageDigest msgDigest = null;
//     try
//     {
//       msgDigest = MessageDigest.getInstance("MD5");
//     } catch (NoSuchAlgorithmException e) {
//       throw new IllegalStateException(
//         "System doesn't support MD5 algorithm.");
//     }
//     try
//     {
//       msgDigest.update(text.getBytes("utf-8"));
//     }
//     catch (Exception e)
//     {
//       throw new IllegalStateException(
//         "System doesn't support your  EncodingException.");
//     }
//
//     byte[] bytes = msgDigest.digest();
//
//     String md5Str = new String(encodeHex(bytes));
//
//     return md5Str;
//   }
//
//   public static char[] encodeHex(byte[] data)
//   {
//     int l = data.length;
//
//     char[] out = new char[l << 1];
//
//     int i = 0; for (int j = 0; i < l; i++) {
//       out[(j++)] = DIGITS[((0xF0 & data[i]) >>> 4)];
//       out[(j++)] = DIGITS[(0xF & data[i])];
//     }
//
//     return out;
//   }

    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
            'E', 'F'};

	/** * @Description:加密-32位小写 * @author:liuyc * @time:2016年5月23日 上午11:15:33 */
	public static String encrypt32(String encryptStr) {
		MessageDigest md5;
		try {
			md5 = MessageDigest.getInstance("MD5");
			byte[] md5Bytes = md5.digest(encryptStr.getBytes(StandardCharsets.UTF_8));
			StringBuffer hexValue = new StringBuffer();
			for (int i = 0; i < md5Bytes.length; i++) {
				int val = ((int) md5Bytes[i]) & 0xff;
				if (val < 16)
					hexValue.append("0");
				hexValue.append(Integer.toHexString(val));
			}
			encryptStr = hexValue.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return encryptStr;
	}

	private static String toHexString(byte[] b) {
		StringBuilder sb = new StringBuilder(b.length * 2);
		for (int i = 0; i < b.length; i++) {
			sb.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]);
			sb.append(HEX_DIGITS[b[i] & 0x0f]);
		}
		return sb.toString();
	}

	/**
	 * 加密解密算法 执行一次加密，两次解密
	 */
	public static String convertMD5(String inStr){

		char[] a = inStr.toCharArray();
		for (int i = 0; i < a.length; i++){
			a[i] = (char) (a[i] ^ 't');
		}
		String s = new String(a);
		return s;

	}

	public static String Bit32(String SourceString) throws Exception {
		MessageDigest digest = MessageDigest.getInstance("MD5");
		digest.update(SourceString.getBytes());
        byte[] messageDigest = digest.digest();
		return toHexString(messageDigest);
	}

	public static String Bit16(String SourceString) throws Exception {
		return Bit32(SourceString).substring(8, 24);
	}
}
